package com.tedu.egweibo.controller;


import com.tedu.egweibo.common.result.JsonResult;
import com.tedu.egweibo.common.result.StatusCode;
import com.tedu.egweibo.mapper.WeiboMapper;
import com.tedu.egweibo.pojo.dto.WeiboDTO;
import com.tedu.egweibo.pojo.entity.User;
import com.tedu.egweibo.pojo.entity.Weibo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/v1/weibo")
@Api(tags = "微博模块")
@Slf4j
@Validated
public class WeiboController {

    @Autowired
    private WeiboMapper weiboMapper;


    // 发布微博
    @PostMapping("/insert")
    @ApiOperation("发布微博功能")
    public JsonResult insertWeibo(@RequestBody WeiboDTO weiboDTO, @ApiIgnore HttpSession session) {
        log.info("发布微博，参数：{}", weiboDTO);
        // 获取当前登录用户
        User user=(User) session.getAttribute("user");
        if (user==null){
            // 未登录
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        Weibo weibo=new Weibo();
        BeanUtils.copyProperties(weiboDTO,weibo);
        weibo.setCreated(new Date());
        weibo.setUserId(user.getId());
        log.debug("要插入的微博信息Weibo：{}",weibo);
        weiboMapper.insertWeibo(weibo);
        log.info("发布成功");
        return JsonResult.success();
    }

    // 获取微博首页列表
    @GetMapping("/selectIndex")
    @ApiOperation("获取微博首页列表")
    public JsonResult selectIndex() {
        log.info("获取微博首页列表");
        return JsonResult.success(weiboMapper.selectIndex());
    }

    // 获取微博详情
    @GetMapping("/selectById")
    @ApiOperation("获取微博详情")
    @ApiImplicitParams({
         @ApiImplicitParam(name = "id", value = "微博id", required = true, dataType = "Integer",example = "1"),
         @ApiImplicitParam(name = "username", value = "用户名", required = true, dataType = "String",example = "test")
    })
    public JsonResult selectById(@RequestParam @Range(min = 1, max = Integer.MAX_VALUE, message = "微博id范围有误") Integer id) {
        log.info("获取微博详情，参数：{}", id);
        return JsonResult.success(weiboMapper.selectWeiboById(id));
    }
}
